﻿//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: OracleStorage.cs
//
//  Description: Provides a storage class for Oracle.
// 
//--------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient;
using Chili.Opf3.Query;
using Chili.Opf3.Query.OPathParser;

namespace Chili.Opf3.Storages.Oracle
{
	/// <summary>Storage class that encapsulates a pyhsical Oracle database.</summary>
	/// <remarks>
	/// 	<para>This class encapsulates a physical Oracle database. It is used to access to
	///     an Oracle database that is installed somewhere on your or on a remote machine. The storage
	///     implements the basic interfaces, such as
	///     <see cref="Opf3.Storages.IStorage">IStorage</see> for the basic storage IO
	///     functinality and
	///     <see cref="Opf3.Storages.ITransactionStorage">ITransactionStorage</see> for the
	///     transaction management.</para>
	/// 	<para><b>Attention:</b> You should not access the methods of the storage directly
	///     but instead register the storage with your instances of the
	///     <see cref="Opf3.ObjectContext">ObjectContext</see>. The
	///     <see cref="Opf3.ObjectContext">ObjectContext</see> accesses the methods internally
	///     to get the objects from the storage.</para>
	/// </remarks>
	/// <example>
	///     The following example shows how you should use the Oracle storage in your
	///     applications. 
	///     <code lang="CS">
	/// // ... Other code
	///  
	/// // Creates a new ObjectContext that uses an Oracle database as storage.
	/// // You should only pass an instance of the storage to your ObjectContext.
	/// // That's it! Nothing more. The methods of the storage are accessed
	/// // by the context internally.
	/// ObjectContext context = new ObjectContext(
	///     new OracleStorage("... some ConnectionString ..."));
	///  
	/// // ... Other code
	///     </code>
	/// </example>
	public class OracleStorage : SqlStorageBase
	{
		private const int _constraintError = 2290;
		private const int _foreignKeyViolation1 = 2291;
		private const int _foreignKeyViolation2 = 2292;
		private const int _primaryKeyViolation = 2437;
		private const int _indexViolation = 1;
		private const int _indexViolation2 = -2146232008;
		private string _sequenceformat = "{0}Sequence";

		/// <summary>
		/// Creates a new instance of the <see cref="OracleStorage">OracleStorage
		/// Class</see>.
		/// </summary>
		/// <param name="connectionString">
		/// Specifies a string that contains the information (for ADO.NET) to connect to storage.
		/// </param>
		/// <exception cref="ArgumentNullException">ConnectionString is null.</exception>
		public OracleStorage(string connectionString) : base(connectionString)
		{
			this.StorageCommandBuilders.Add(new OracleCommandBuilder());
			this.StorageCommandBuilders.Add(new SqlQueryCommandBuilder());
		}

		/// <summary>
		/// Creates a new instance of the <see cref="OracleStorage">OracleStorage
		/// Class</see>.
		/// </summary>
		/// <param name="user">Specifies the name of the user that connects to the storage.</param>
		/// <param name="password">Specifies the password of the user that connects to the storage.</param>
		/// <param name="host">
		/// Specifies the database's hostname (Name of the machine where the database is
		/// installed).
		/// </param>
		/// <exception cref="ArgumentNullException">User is null, password is null or host is null.</exception>
		public OracleStorage(string user, string password, string host) 
			: this(string.Format(@"Server={0};User ID={1};Password={2};Persist Security Info=True", host, user, password))
		{
			if (user == null)
				throw new ArgumentNullException("user");
			if (password == null)
				throw new ArgumentNullException("password");
			if (host == null)
				throw new ArgumentNullException("host");
		}

		/// <summary>
		/// Specifies the format string for sequences.
		/// </summary>
		/// <remarks>
		/// The SequenceFormat string allows you to specify a format string for the sequence names.
		/// The default value for a sequence is {0}Sequence. {0} stands for the name of the entity
		/// for which this sequence is generated. You may also add {1} which is then the name of 
		/// the field for which the sequence is create. 
		/// </remarks>
		/// <example>
		/// This example shows the sequence format strings for an entity named "USER". The sequence is generated
		/// for the field "ID".
		/// <code>
		///		{0}Sequence = USERSequence
		///     {0}_s1 = USER_s1
		///     {0}{1}Sequence = USERIDSequence
		///     {0}_s{1} = USER_sID
		/// </code>
		/// </example>
		public string SequenceFormat
		{
			get { return _sequenceformat; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value");
				_sequenceformat = value;
			}
		}

		#region Overridden Member

		/// <summary>
		/// Executes a command on the storage that does not expect any results. It the method
		/// returns an argument it is used by the framework to set the
		/// <see cref="Opf3.FieldAttribute.AutoNumber">AutoNumber</see> property of the persistent
		/// object.
		/// </summary>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageConstraintException">A constraint of the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.ForeignKeyViolationException">A foreign key in the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">A duplicate primary key 
		/// is inserted in the storage.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">An index has been violated.</exception>
		/// <exception cref="Opf3.Storages.StorageException">Any other unexpected storage exception.</exception>
		/// <exception cref="ArgumentNullException">Query is null.</exception>
		public override object ExecuteCommand(IQuery query)
		{
			if (query == null)
				throw new ArgumentNullException("query");

			try
			{
				object autoValue = null;
				CompiledQuery compiledQuery = query.ToCompiledQuery(this);
				Tracing.Current.TraceStorageIO(compiledQuery);

				// Prepare the command for execution.
				using (IDbCommand command = this.PrepareCommand(compiledQuery))
				{
					command.ExecuteNonQuery();

					if (query.QueryType == QueryTypes.Insert && compiledQuery.AutoNumberItems != null)
					{
						// Assumes that only one autonumber is in the query. Only the first one is returned.
						foreach (OracleParameter parameter in command.Parameters)
						{
							// HACK: The first parameter with output is returned as autonumber.
							if (parameter.Direction == ParameterDirection.Output)
							{
								autoValue = parameter.Value;
								Tracing.Current.TraceStorageIO("Autonumber value returned: " + autoValue);
								break;
							}
						}
					}
					// If no transaction is active we can close the connection after executing the command.
					if (!IsTransactionActive)
						command.Connection.Close();
				}
				return autoValue;
			}
			catch (OracleException ex)
			{
				if (ex.ErrorCode == _constraintError)
					throw new StorageConstraintException(ex.Message, ex, query);
				else if (ex.ErrorCode == _foreignKeyViolation1 || ex.ErrorCode == _foreignKeyViolation2)
					throw new ForeignKeyViolationException(ex.Message, ex, query);
				else if (ex.ErrorCode == _primaryKeyViolation)
					throw new PrimaryKeyViolationException(ex.Message, ex, query);
				else if (ex.ErrorCode == _indexViolation || ex.ErrorCode == _indexViolation2)
					throw new IndexViolationException(ex.Message, ex, query);
				else
					throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>
		/// Executes and compiles the <see cref="Opf3.Query.IQuery">IQuery</see> and returns
		/// an <see cref="Opf3.ObjectReader{T}">ObjectReader</see> with the resultsset.
		/// </summary>
		/// <param name="context">
		/// 	<see cref="Opf3.ObjectContext">ObjectContext</see> that is connected with the
		/// <see cref="Opf3.ObjectReader{T}">ObjectReader</see>.
		/// </param>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageException">An unexpected storage exception has happened.</exception>
		public override ObjectReader<T> ExecuteReader<T>(ObjectContext context, IQuery query)
		{
			try
			{
				return base.ExecuteReader<T>(context, query);
			}
			catch (OracleException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>Creates a new storage dependent connection object.</summary>
		/// <returns>Returns an instance of a storage dependent connection object.</returns>
		public override IDbConnection CreateConnection()
		{
			// Create the connection and open it.
			OracleConnection connection = new OracleConnection(this.ConnectionString);
			connection.Open();
			return connection;
		}

		/// <summary>Creates a new storage dependent command object.</summary>
		/// <returns>Returns an instance of a storage dependent command object.</returns>
		public override IDbCommand CreateCommand()
		{
			return new OracleCommand();
		}

		/// <summary>Creates and populates a storage dependent parameter with data.</summary>
		/// <returns>
		/// The name of the storage parameter should be set to a valid parameter name (one
		/// that is supported by the storage) while creating the parameter.
		/// </returns>
		/// <param name="index">Index of the storage parameter.</param>
		/// <param name="name">Name of the storage parameter.</param>
		/// <param name="value">Value of the storage parameter.</param>
		/// <param name="type">The type of the value argument. This information is useful if the value is null.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override IDataParameter CreateParameter(int index, ref string name, object value, Type type)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			// Set the name for the parameter.
			name = ":" + name;

			return new OracleParameter(name, value == null ? DBNull.Value : value);
		}

		/// <summary>Transforms the parameter to a valid field.</summary>
		/// <returns>Returns a string that represents a valid field name.</returns>
		/// <remarks>
		/// This method returns a field name that is valid for the current storage. For some
		/// storages it is a better choice to start each field name with a '[' and end with a ']'
		/// (Ms Access) - This method could wrap each field name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name for the field that is transformed.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidFieldName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			return name;
		}

		/// <summary>
		/// Transforms the name of the entity to a valid entity name.
		/// </summary>
		/// <returns>Returns a string that represents a valid entity name.</returns>
		/// <remarks>
		/// This method returns an entity name that is valid for the current storage. For
		/// some storages it is a better choice to start each entity name with a '[' and end with a
		/// ']' (Ms Access) - This method could wrap each entity name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name of the entity.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidEntityName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			return name;
		}

		#endregion
	}
}
